package zhaomh.zhlib.mixin;

import net.minecraft.client.gui.screen.ChatScreen;
import net.minecraft.util.StringHelper;
import org.apache.commons.lang3.StringUtils;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import zhaomh.zhlib.ZhLib;
import zhaomh.zhlib.events.impl.ChatEvent;
import zhaomh.zhlib.ModInstance;

@Mixin(ChatScreen.class)
public class ChatMixin implements ModInstance {

	@Inject(at = @At("HEAD"), method = "sendMessage", cancellable = true)
	public void sendMessage(String chatText, boolean addToHistory, CallbackInfo ci) {
		ChatEvent event = ZhLib.getGameEventManager().call(new ChatEvent(chatText, addToHistory));
		if (event.isCancelled())
			return;
		chatText = event.getMessage();
		addToHistory = event.isAddToHistory();
		chatText = StringHelper.truncateChat(StringUtils.normalizeSpace(chatText.trim()));
		if (!chatText.isEmpty()) {
			if (addToHistory) {
				mc.inGameHud.getChatHud().addToMessageHistory(chatText);
			}

			if (chatText.startsWith("/")) {
				mc.player.networkHandler.sendChatCommand(chatText.substring(1));
			} else {
				mc.player.networkHandler.sendChatMessage(chatText);
			}
		}
		ci.cancel();
	}

}